package com.cosmoplat.xikai.business.modbus.listerner;

import com.cosmoplat.xikai.business.domain.DeviceLog;
import com.cosmoplat.xikai.business.domain.DeviceThingModel;
import com.cosmoplat.xikai.business.enums.DeviceParamsEnum;
import com.cosmoplat.xikai.business.scada.ScadaData;
import com.serotonin.modbus4j.ProcessImageListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @author zhangyanda
 */
@Component
@Slf4j
public class BasicProcessImageListener implements ProcessImageListener {

    @Autowired
    private ScadaData scadaData;

    @Override
    public void coilWrite(int offset, boolean oldValue, boolean newValue) {
    }

    @Override
    public void holdingRegisterWrite(int offset, short oldValue, short newValue) {
        if (oldValue != newValue) {
            log.info("HoldRrgister at " + offset + " was set from " + oldValue + " to " + newValue);
        }
        String result = String.valueOf(newValue);

        //根据该地址位获取该设备物模型
        DeviceThingModel deviceThingModel = scadaData.getDeviceThingModel(String.valueOf(offset), 2);
        DeviceLog runStatusLog = scadaData.getDeviceLog(DeviceParamsEnum.RUN_STATE.getName());
        if (deviceThingModel != null) {
            //根据协议进行解析
            //将数据保存到静态map当中
            DeviceLog deviceLog = new DeviceLog(deviceThingModel.getDeviceId(), deviceThingModel.getId(), result, deviceThingModel.getType(), new Date(), runStatusLog == null ? null : runStatusLog.getVal(), new Date());
            //判断是否是多地址位数据
            if (deviceThingModel.getNumberOfPoints() == 4) {
                scadaData.putMultiRegister(deviceThingModel, deviceLog);
            } else {
                scadaData.addDeviceLog(deviceThingModel.getIdentifier(), deviceLog);
            }
        } else if (offset >= 200) {
            //判断当前地址位是否＞200(发送修改地址位都＞200所以进行判断)
            //获取当前物模型
            DeviceThingModel thingModel = scadaData.getDeviceThingModel(String.valueOf(offset - 200), 2);
            if (thingModel != null) {
                //如果有该物模型获取当前接收的数据
                //将接收的地址返回值放到专门发送的 map 当中
                scadaData.putSendMap(thingModel.getIdentifier(), result);
            }
        }

    }

}